#import "RNRootHeaderViewController.h"
#import "Category.h"
#import "Catalog.h"

@implementation RNRootHeaderViewController

@synthesize titleField = titleField_;

+(NSSet *)keyPathsForValuesAffectingRootObject {
    return [NSSet setWithObject:@"parent.rootObject"];
}

-(id)rootObject {
    return [[self parent] valueForKey:@"rootObject"];
}

+(NSSet *)keyPathsForValuesAffectingPathString {
    return [NSSet setWithObject:@"rootObject"];
}

-(NSString *)pathString {
    if (![self rootObject])
        return nil;
    id parent = [[self rootObject] parent];
    if (!parent)
        return [[self rootObject] isKindOfClass:[Category class]] ? @"/Catalog" : nil;
    NSMutableString *pathString = [NSMutableString stringWithFormat:@"%@", [parent title]];
    parent = [parent parent];
    while (parent != nil) {
        [pathString insertString:[NSString stringWithFormat:@"%@/", [parent title]] atIndex:0];
        parent = [parent parent];
    }
    [pathString insertString:([[self rootObject] isKindOfClass:[Category class]] ? @"/Catalog/" : @"/") atIndex:0];
    return pathString;
}

-(IBAction)rootPathClicked:(id)sender {
    NSPathComponentCell *clickedCell = [(NSPathControl *)sender clickedPathComponentCell];
    if (!clickedCell)
        return;
    NSArray *pathCells = [(NSPathControl *)sender pathComponentCells];
    id currentObject = [self rootObject];
    for (NSUInteger parentLevel = [pathCells count] - [pathCells indexOfObject:clickedCell]; parentLevel > 0; parentLevel--)
        currentObject = [currentObject parent];
    if (!currentObject)
        currentObject = [Catalog sharedCatalog];
    [[self parent] setValue:currentObject forKey:@"rootObject"];
}

@end